﻿<!DOCTYPE html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加销售订单</title>
    <link rel="stylesheet" href="../css/from.css">
    <link rel="stylesheet" href="../themes/default/easyui.css">
    <link rel="stylesheet" href="../themes/icon.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/jquery.easyui.min.js"></script>
    <script src="../js/easyui-lang-zh_CN.js"></script>
    <script>
        function loadSupplier() {
          $("#list").dialog({
                title: '选择客户',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           });
        }
        
        function closeSupplier(){
        	$("#list").dialog("destroy");
        	$("#supplier_list_parent").html("<div id='list'  style='display: none' data-options='onClose:function(){closeSupplier()}'>"+
        	"<iframe src='supplier_list.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
         function loadPart() {
         var customName=$("#customName").textbox('getValue');
         if(customName!=null&&customName!=''){
            $("#partList").dialog({
                title: '选择配件',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
            });
          }else{
             alert("请选择客户！");
          }  
         }
        function closePart() {
            $("#partList").dialog("destroy");
        	$("#part_List_parent").html("<div id='partList'  style='display: none' data-options='onClose:function(){closePart()}'>"+
        	"<iframe src='addPart.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
       function loadOfferPriceBill() {
         var customName=$("#customName").textbox('getValue');
         if(customName!=null&&customName!=''){
            $("#offerPriceBillList").dialog({
                title: '选择报价表',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
            });
          }else{
             alert("请选择客户！");
          }  
        }
        
        function closeOfferPriceBill() {
            $("#offerPriceBillList").dialog("destroy");
        	$("#offerPriceBill_List_parent").html("<div id='offerPriceBillList'  style='display: none' data-options='onClose:function(){closeOfferPriceBill()}'>"+
        	"<iframe src='addOfferPriceBill.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
       $(function(){
              $("#generatingParts").datagrid({
                checkOnSelect:true,
                rownumbers:true,
                columns:[[
                    {field:'billCode',title:'报价单号',width:130},
                    {field:'code',title:'配件编号',width:130},
                    {field:'partName',title:'配件名称',width:180},
                    {field:'partBrand',title:'配件品牌',width:120},
                    {field:'partNo',title:'配件型号',width:100},
                    {field:'amount',title:'数量',width:100,
                        formatter:function(value,row,index){
                    	    if(row.sellPrice==null){
                    	     return value;
                    	    }
                            return '<input name="amount" onchange="onChange_Amount_SellPrice('+index+',this)" type="number" value="'+value+'" style="width:30px;"/>';
                        } 
                    },
                    {field:'sellPrice',title:'单价',width:100,
                          formatter:function(value,row,index){
                           if(row.sellPrice==null){
                    		return null;
                    	   }
                            return '<input name="sellPrice" onchange="onChange_Amount_SellPrice('+index+',this)" type="number" value="'+value+'" style="width:50px;"/>';
                          }
                    },
                    {field:'price',title:'总金额',width:100,
                        formatter:function(value,row,index){
                         	if(row.sellPrice==null){
	                    		return "￥"+value;
	                    	}
                            return "￥"+value;
                        }
                    },
                    {field:'memo',title:'备注',width:150,
                         formatter:function(value,row,index){
                            if(row.sellPrice==null){
                    		return null;
                    	    }
                    	    if(value==null||value==''){
                    	      value='';
                    	    }
                            return '<input name="memo" onchange="onChange_Memo('+index+',this)" type="text" value="'+value+'" style="width:170px"/>';
                          }
                    },
                    {field:'opt',title:'操作',width:100,formatter:function (value,row,index) {
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            var context="<a href=\"javascript:del('"+index+"')\">删除</a>&nbsp;&nbsp;" 
                            return context;
                        }
                    }

                ]],
                toolbar:'#wu_toolbar'
               /*  onClickCell:onClickCell */
            });
       
       
             $("#search_btn").click(function(){
	           var form=$("#form1");
  		       $("#providerList").datagrid('load',serializeForm(form));
             });
       
        var path=$("#path").val();
        $.ajax({
		type:"post",//请求类型
		url:path+"/sellorderbill/makenewcode?prefix=XS", 
		dataType:"json",//ajax接口（请求url）返回的数据类型
		success:function(data){//data：返回数据（json对象）
		   $("#code").textbox({'value':data.result});
		}
	    });
	    var newdate=new Date();
	    $("#orderTime").datetimebox("setValue",myformatter(newdate));
	    $("#yewurenyuan").textbox({'value':'jr_democ'});
	    
	    
	    $("#save").click(function(){
	     $.messager.confirm('确认','确认想要添加该销售单吗？',function(r){
           if (r==true){
		    var form=$("#form").serialize();
		    var deliveryTime=$("#deliveryTime").textbox('getText');
		    var oldRow=$('#generatingParts').datagrid('getRows');
		    var data=JSON.stringify($('#generatingParts').datagrid('getData').rows);
		    if(deliveryTime==null || deliveryTime==''){
			   $.messager.alert('我的消息','请填写交货时间!','warning');
		    }else{
			    if(oldRow==null||oldRow==''){ 
			       $.messager.alert('我的消息','没有添加配件信息，请添加配件后再保存!','warning');
			    }else{ 
			       var money=parseFloat(oldRow[oldRow.length-1]['price']);
			       $.ajax({
				      type:"post",//请求类型
				      url:path+"/sellorderbill/addSellOrderBill?"+form, 
				      data:{"data":data,"money":money},
				      dataType:"json",//ajax接口（请求url）返回的数据类型
				      success:function(data){//data：返回数据（json对象）
				         if(data.result=="error"){
				          alert("添加失败");
				         }
				         else if(data.result=="success"){
				          alert("添加成功");
		                  parent.addTabs('销售订单管理','goods/salesOrderManagement.jsp');
				          parent.closeTabs('销售订单');
				         }
				      }  
			       }); 
			    }
			} 
		   }
         }); 	 
	    });
       });
       
         function onChange_Amount_SellPrice(index,input){
          var amount=$(input).parent().parent().parent().find('[name="amount"]').val();
          var sellPrice=$(input).parent().parent().parent().find('[name="sellPrice"]').val();
          var price=parseFloat(amount)*parseFloat(sellPrice);
          $("#generatingParts").datagrid('updateRow',{
               index: index,
	           row: {
		           amount: amount,
		           sellPrice: sellPrice,
		           price:price
	           }
          });
          oldRow=$("#generatingParts").datagrid('getRows');
          $("#generatingParts").datagrid('deleteRow',oldRow.length-1);
		  $("#generatingParts").datagrid('appendRow',{
                	'partBrand':"合计",
                	'amount':total('amount'),
                	'price':total('price')
          });
        }
        
         function onChange_Memo(index,input){
          var memo=$(input).parent().parent().parent().find('[name="memo"]').val();
          $("#generatingParts").datagrid('updateRow',{
               index: index,
	           row: {
		          memo:memo
	           }
          });
         } 
        
        function del(index){
           //删除当前行
           $('#generatingParts').datagrid('deleteRow',index);
           //拿到之前的数据并重新封装，刷新index
           var oldData=$("#generatingParts").datagrid('getData');
           $("#generatingParts").datagrid('loadData',oldData);
           oldRow=$("#generatingParts").datagrid('getRows');
           $("#generatingParts").datagrid('deleteRow',oldRow.length-1);
		   $("#generatingParts").datagrid('appendRow',{
               'partBrand':"合计",
               'amount':total('amount'),
               'price':total('price')
          });
        }
        
        //将表单序列化
		function serializeForm(form){
			var obj={};
			$.each(form.serializeArray(),function(index){
				  if(obj[this['name']]){
					obj[this['name']]=obj[this['name']]+','+this['value']
				 }else{
				   obj[this['name']]=this['value'];
				 }
			});
			return obj;
        }
        
        function myformatter(date){
          var y=date.getFullYear();
          var m=date.getMonth()+1;
          var d=date.getDate();
          var hour=date.getHours();
          var mini=date.getMinutes();
          var sec=date.getSeconds();
          return y+"-"+(m<10?('0'+m):m)+"-"+(d<10?('0'+d):d)+" "+(hour<10?('0'+hour):hour)+":"+(mini<10?('0'+mini):mini)+":"+(sec<10?('0'+sec):sec);
        }
        //用于将子页面的数据绑定到相关元素上
        function bindValue(data){
        	var name=data[0];
        	var linkman=data[1];
        	var phone=data[2];
        	var fax=data[3];
        	$('#customName').textbox('setValue',name);	
        	$('#linkman').textbox('setValue',linkman);	
        	$('#phone').textbox('setValue',phone);	
        	$('#fax').textbox('setValue',fax);	
        }
        
        function clearPartDatagrid(){
        	 $("#generatingParts_parent").html("<div id='generatingParts' class='easyui-datagrid'></div>"); 
             $("#generatingParts").datagrid({
                checkOnSelect:true,
                rownumbers:true,
                columns:[[
                    {field:'billCode',title:'报价单号',width:130},
                    {field:'code',title:'配件编号',width:130},
                    {field:'partName',title:'配件名称',width:180},
                    {field:'partBrand',title:'配件品牌',width:120},
                    {field:'partNo',title:'配件型号',width:100},
                    {field:'amount',title:'数量',width:100,
                        formatter:function(value,row,index){
                    	    if(row.sellPrice==null){
                    	     return value;
                    	    }
                            return '<input name="amount" onchange="onChange_Amount_SellPrice('+index+',this)" type="number" value="'+value+'" style="width:30px;"/>';
                        } 
                    },
                    {field:'sellPrice',title:'单价',width:100,
                          formatter:function(value,row,index){
                           if(row.sellPrice==null){
                    		return null;
                    	   }
                            return '<input name="sellPrice" onchange="onChange_Amount_SellPrice('+index+',this)" type="number" value="'+value+'" style="width:50px;"/>';
                          }
                    },
                    {field:'price',title:'总金额',width:100,
                        formatter:function(value,row,index){
                         	if(row.sellPrice==null){
	                    		return "￥"+value;
	                    	}
                            return "￥"+value;
                        }
                    },
                    {field:'memo',title:'备注',width:190,
                         formatter:function(value,row,index){
                            if(row.sellPrice==null){
                    		return null;
                    	    }
                    	    if(value==null||value==''){
                    	      value='';
                    	    }
                            return '<input name="memo" onchange="onChange_Memo('+index+',this)" type="text" value="'+value+'" style="width:170px"/>';
                          }
                    },
                    {field:'opt',title:'操作',width:100,formatter:function (value,row,index) {
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            var context="<a href=\"javascript:del('"+index+"')\">删除</a>&nbsp;&nbsp;" 
                            return context;
                        }
                    }

                ]],
                toolbar:'#wu_toolbar'
               /*  onClickCell:onClickCell */
            });
        }
        
         //用于将子页面的数据绑定到相关元素上
         function addpart(row){
            var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['code']==row[i]['code']){
         		       alert("不能添加重复配件");
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addPartsToPage(row[i]);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addPartsToPage(row[i]);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addPartsToPage(row[i]);
					}	
                }
              }
              closePart();
         }
        
        //用于将子页面的数据绑定到相关元素上
         function addOfferPriceBill(row){
             var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['code']==row[i]['code']&&oldRow[j]['billCode']==row[i]['billCode']){
         		       alert("不能添加重复配件");
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addOfferPriceBillToPage(row[i]);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addOfferPriceBillToPage(row[i]);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addOfferPriceBillToPage(row[i]);
					}	
                }
              }	
              closeOfferPriceBill();
         }
        
        function addPartsToPage(row){
           $('#generatingParts').datagrid('appendRow',{
				billCode: row.billCode,
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: 1,
				sellPrice: row.sellPrice,
				price: row.sellPrice,
				memo: row.memo,
				opt: ''
		   });
		   
		   $('#generatingParts').datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           });
        }
         function addOfferPriceBillToPage(row){
           $('#generatingParts').datagrid('appendRow',{
				billCode: row.billCode,
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: row.amount,
				sellPrice: row.sellPrice,
				price: row.sellPrice*row.amount,
				memo: row.memo,
				opt: ''
		   });
		   
		   $('#generatingParts').datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           });
        }
        
          function total(col){
        	var rows=$("#generatingParts").datagrid('getRows');
        	var total=0;
        	for(var i=0;i<rows.length;i++){
        		total+=parseFloat(rows[i][col]);
        	}
        	return total;
          }
           
         function reload(){
            window.location.reload();
         }  
         
         function Close(){
            parent.closeTabs("销售订单");
         }
         
          function Auditing(){
            $.messager.confirm('确认','确认想要审核该销售单吗？',function(r){
              if (r==true){
                    var form=$("#form").serialize();
				    var deliveryTime=$("#deliveryTime").textbox('getText');
				    var oldRow=$('#generatingParts').datagrid('getRows');
				    var data=JSON.stringify($('#generatingParts').datagrid('getData').rows);
				    if(deliveryTime==null || deliveryTime==''){
					   $.messager.alert('我的消息','请填写交货时间!','warning');
				    }else{
					    if(oldRow==null||oldRow==''){ 
					       $.messager.alert('我的消息','没有添加配件信息，请添加配件后再保存!','warning');
					    }else{ 
					       var money=parseFloat(oldRow[oldRow.length-1]['price']);
					       $.ajax({
						      type:"post",//请求类型
						      url:"/kxmanage/sellorderbill/addAuditing?"+form, 
						      data:{"data":data,"money":money},
						      dataType:"json",//ajax接口（请求url）返回的数据类型
						      success:function(data){//data：返回数据（json对象）
						         if(data.result=="error"){
						          alert("审核失败");
						         }
						         else if(data.result=="success"){
						          alert("审核成功");
				                  parent.addTabs('销售订单管理','goods/salesOrderManagement.jsp');
						          parent.closeTabs('销售订单');
						         }
						      }  
					       }); 
					    }
					}  
              }
            });
         }  
    </script>
    <style>
        body {
            font-size:12px;
            padding:10px
        }
        .l-table-edit {
          border-collapse:collapse;
          border-spacing:0;
        }
        .l-table-edit-td {
            padding:4px;
            font-size:12px;
            border:1px solid #84a0c4 
        }
        
    </style>


</head>
<body>
<form name="form"  id="form" action="" method="post">
    <table cellpadding="0" cellspacing="0" class="l-table-edit" style="width:100%">
        <tr >
            <td width="17%"  align="right" class="l-table-edit-td">订单编号：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" readonly="readonly" class="easyui-textbox" id="code" value="" name="code"  maxlength="100" ltype="text" style="height:20px" /></td>
            <td width="13%"  align="right" class="l-table-edit-td">订单日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input  type="text" id="orderTime"  name="orderTime" value="" maxlength="30" class="easyui-datetimebox" style="height:20px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">
                <a href="#" onclick="loadSupplier()">客户名称：</a>
            </td>
            <td align="left" class="l-table-edit-td" width="27%">
                <input type="text" id="customName" name="customName" value="" class="easyui-textbox"  maxlength="100" ltype="text"  style="height:20px"/>
            <td width="13%" align="right" class="l-table-edit-td">联系人员：</td>
            <td align="left" class="l-table-edit-td" width="43%">
                <input name="linkman" type="text" id="linkman" value="" class="easyui-textbox" maxlength="30" ltype="text" style="height:20px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">电话：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" id="phone" name="phone" class="easyui-textbox" value=""  maxlength="50" ltype="text" style="height:20px"/></td>
            <td width="13%" align="right" class="l-table-edit-td">传真：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input type="text" id="fax" name="fax" class="easyui-textbox" value="" maxlength="50"  ltype="text" style="height:20px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">运输方式：</td>
            <td width="27%" align="left" class="l-table-edit-td">
             <select name="shippingMode" id="shippingMode" class="easyui-combobox" style="width:100px;height:20px" panelHeight="150px">
                 <option value="1">圆通快递</option> 
                 <option value="2">中通快递</option> 
             </select>
            </td>
            <td width="13%" align="right" class="l-table-edit-td">业务人员：</td>
            <td width="43%"align="left" class="l-table-edit-td"><input type="text" readonly="readonly" class="easyui-textbox"  id="yewurenyuan" name="yewurenyuan" value="" maxlength="50"  ltype="text" style="height:20px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">备注：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" class="easyui-textbox" id="memo" name="memo" value="" maxlength="50" ltype="text" style="height:20px"/></td>
            <td width="13%" align="right" class="l-table-edit-td">交货日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input type="text"  class="easyui-datetimebox" id="deliveryTime" name="deliveryTime" value="" maxlength="50"  ltype="text" style="height:20px"/></td>
        </tr>
    </table>
</form>
<br>
<input type="hidden" id="path" value="${pageContext.request.contextPath}"/>
<input  type="button" value="新   增" onclick="reload()" style="width:60px">
<a href="javascript:loadOfferPriceBill()"><input  type="button" value="选报价单" style="width:60px"></a>
<a href="javascript:loadPart()"><input  type="button" value="添加配件" style="width:60px"></a>
<a href="javascript:;"><input id="save" type="button" value="保存" style="width:60px"></a>
<input  type="button" id="auditing" onclick="Auditing()" value="审核" style="width:60px">
<input  type="button" onclick="Close()" value="关闭" style="width:60px">
<br/><br/>
<div id="generatingParts_parent">
<div id="generatingParts" class="easyui-datagrid">
</div>
</div>
<div id="supplier_list_parent">
<div id="list"  style="display: none" data-options='onClose:function(){closeSupplier()}'>
    <iframe src='supplier_list.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>
<div id="part_List_parent">
<div id="partList"  style="display: none"  data-options='onClose:function(){closePart()}'>
    <iframe src='addPart.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>
<div id="offerPriceBill_List_parent">
<div id="offerPriceBillList"  style="display: none"  data-options='onClose:function(){closeOfferPriceBill()}'>
    <iframe src='addOfferPriceBill.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>
</body>
</html>